#!/usr/bin/env python
#  -*- coding: UTF-8 -*-
import os
import uuid

from wechat import settings


def UploadFiles(fileList):
    userdata = []
    try:
        if not fileList:
            raise Exception("没有上传文件")
        for f in fileList:
            # 上传文件，文件名生成guid.jpg,保留原文件名
            struuid = str(uuid.uuid4())
            originalFileName = f.name
            ext = originalFileName[originalFileName.index("."):len(originalFileName)]
            fName = struuid + ext
            destination = open(os.path.join(settings.MEDIA_ROOT + '/upload/', fName), 'wb+')
            for chunk in f.chunks():
                destination.write(chunk)
            destination.close()
            fileUrl = "/%s%s" % (settings.MEDIA_URL, fName)
            info = {}
            info["file_name"] = originalFileName
            info["file_url"] = fileUrl
            userdata.append(info)
    except Exception as e:
        return {
            "status": 0,
            "message": u"文件上传失败:%s" % e.message,
            "data": []
        }
    return {
        "status": 1,
        "message": u"文件上传成功",
        "data": userdata
    }
